<?php

namespace app\api\controller;

use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Db;

use think\Config;
use think\Validate;//验证
use fast\Random;
use fast\Http;

use app\api\controller\Tpmecms;



/**
 * 我的🏠
 */
class Me extends Tpmecms
{

    protected $noNeedLogin = ['get_openid','get_user_mobile'];
    protected $noNeedRight = ['*'];



    public function _initialize()
    {
        parent::_initialize();
        
        $this->car_fields = ['model','number','owner','end_time','regtime'];//,'driver_lic','car_type''use_type',

    }

    /**
     * 获取openid
     * @ApiSummary (里面有token，提交接口都要带上)
     * @param [type] $code
     * @return void
     */
    public function get_openid($code=null){
    
        $app = $this->get_app();
        $user = $app->auth->session($code);
        if(!empty($user['errcode'])){
            halt($user);
        }
        $openid = $user['openid'];
     
        $data = array();
        $data['openid'] = $openid;
        $user_data = Db::name('user')->where('openid',$openid)->find();
        if($user_data){
            $ret = $this->auth->direct($user_data['id']);
            $data = $this->auth->getUserinfo();
            // $data['uid'] = $user_data['id'];


            // $data['logintime'] = time();
            //开放平台
            if(empty($user_data['unionid']) && (!empty($user['unionid']))){
                Db::name('user')->where('openid',$openid)->update(['unionid'=>$user['unionid']]);
            }
        }else{

            $indata['openid'] = $openid;
            $indata['createtime'] = time();
            $indata['jointime'] = $indata['createtime'];
            $indata['joinip'] = $this->request->ip();
            $indata['logintime'] = time();
            $indata['status'] = 'normal';

            // $indata['stateswitch'] = 1;

            //开放平台
            if(!empty($user['unionid'])){
                $indata['unionid'] = $user['unionid'];
            }
            
     
            $id = Db::name('user')->insertGetId($indata);
            $ret = $this->auth->direct($id);

            $data = $this->auth->getUserinfo();
        }
        
        // $data['is']     = $data['uid'];//未知
        return json($data);
    }





    /**
     * 修改小程序用户的昵称和头像
     *
     * @param string $nickname 昵称
     * @param string $img 头像
     * @return void
     */ 
    public function che_user($nickname,$img)
    {   
        
        $u['id'] = $this->auth->id;
        $json['code'] = -1;
        $json['msg'] = '修改失败';

        $data['nickname'] = $nickname;
        $data['avatar'] = $img;
        $res = Db::name('user')->where($u)->update($data);
        if($res){
            $json['code'] = 1;
            $json['msg'] = '修改成功';
        }
        return json($json);
    }


    /**
     * 获取用户信息
     *
     * @return void
     */
    public function get_user()
    {
        

        $list['user'] = Db::name('user')->find($this->auth->id);
        if(strlen($list['user']['avatar'])>0){
            $url = $list['user']['avatar'];
            $img = file_get_contents($url);
            file_put_contents('assets/img/wx/'.$this->auth->id.'.png',$img);
            $list['user']['img'] = '/assets/img/wx/'.$this->auth->id.'.png';
        }
        
        // $list['user']['play_min'] = ceil($this->get_user_paly_time($this->auth->id)/60);
       
        // $goods = Db::name('goods')->where('uid',$this->auth->id)->find();
        
     
        // $list['goods'] = $goods;
        // $list['user']['vip_stime'] = date('Y-m-d',$list['user']['vip_stime']);
        $list['ltder'] = Db::name('ltder')->where('uid',$this->auth->id)->find();


        return json($list);
    }



    /**
     * 修改上级
     *
     * @param string $pid 用户id
     * @return void
     */
    public function update_pid($pid)
    {
        
        $user = Db::name('user')->find($this->auth->id);
        if($user){
            if(!empty($user['pid'])){
                $this->error('已经有上级'.$user['pid']);
            }
        }

        
        $res_up = Db::name('user')->where('id',$this->auth->id)->update(['pid'=>$pid]);
        if($res_up){
            // $this->AddGift($this->auth->id,$pid);//添加礼包邀请
            $this->success('绑定成功');
        }
    } 
    


    /**
     * 小程序授权获取手机号
     *
     * @param string $code
     * @return void
     */    
    public function get_user_mobile($code=null)
    {   
        $app = $this->get_app();
        $data = $this->request->param();
        $user = $app->auth->session($code);
        $iv = $data['iv'];
        $encryptedData = $data['encryptedData'];

        $session = $user['session_key'];//$app->sns->getSessionKey($code);
        $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptedData);

        $updata['mobile']=$decryptedData['phoneNumber'];
        
       
        //绑定录入的 用户
        if(!Db::name('user')->where('openid',$user['openid'])->value('pid')){
            $pid = Db::name('bind')->where('tel',$decryptedData['phoneNumber'])->value('pid');
            if($pid){
                $updata['pid'] = $pid;
                // $this->AddGift($this->auth->id,$pid);//添加礼包邀请
            }

        }
        //修改手机号
        Db::name('user')->where('openid',$user['openid'])->update($updata);
        
        return $decryptedData['phoneNumber'];
        // halt($decryptedData);
        
    }




    //  /**
    //  * 申请老师
    //  *
    //  * @param string $name 姓名
    //  * @param string $wechat 微信号
    //  * @param string $ltd 公司
    //  * @param string $email 邮箱
    //  * @param string $tel 电话
    //  * @param string $inviter 邀请人
    //  * @param string $ps 备注
    //  * @return void
    //  */
    // public function apply_teacher()
    // {
        
    //     $data['name'] = $this->request->param('name');
    //     $data['wechat'] = $this->request->param('wechat');
    //     $data['ltd'] = $this->request->param('ltd');
    //     $data['email'] = $this->request->param('email');
    //     $data['tel'] = $this->request->param('tel');
    //     $data['inviter'] = $this->request->param('inviter');    
    //     $data['ps'] = $this->request->param('ps');       
    //     $data['uid'] = $this->auth->id;

    //     $res = Db::name('teacher')->where($data)->find();
    //     if($res){
    //         $this->error('已提交过');
    //     }
    //     $data['time'] = time();
    //     $data['status_switch'] = 0;
    //     $res = Db::name('teacher')->insertGetId($data);
    //     if($res){
    //         $this->success('申请成功');
    //     }
    // }







    /**
     * 获取我的邀请人数
     *
     * @param boolean $self 掉接口不需要传
     * @return void
     */
    public function user_get_my_share_num($self=false)
    {
        
        $num = Db::name('user')
                    ->where('pid',$this->auth->id)
                    ->count();
        if($self){
            return $num; 
        }
        $this->success('👌',$num);
        

    }




    /**
     * 获取我的邀请列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @param string $mobile 手机号搜索
     * @return void
     */
    public function get_share_list($page = 1,$limit = 10,$mobile=null)
    {
        $where['pid'] = ['=',$this->auth->id];
        if($mobile){
            $where['mobile'] = ['like','%'.$mobile.'%'];
        }
        $list = Db::name('user')
                    ->where($where)
                    ->order('createtime desc')
                    ->page($page,$limit)
                    ->field([ '*,FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%m:%s") as date'])
                    ->select();
        $this->success(sizeof($list), $list);
    }





    /**
     * 获取邀请礼包列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @param string $status 状态:1=未满5位,2=待领取礼包,3已领取
     * @return void
     */
    public function get_gift_list($page=1,$limit=10,$status=null)
    {
        $list = Db::name('gift')
            ->where('uid',$this->auth->id)
            ->page($page,$limit)
            ->select();
        if($list){
            foreach ($list as $key => &$val) {
                $val['user_list'] = Db::name('user')->where('id','in',$val['user_ids'])->select();
            }
        }
        $this->success('ok',$list);
    }


    /**
     * 获取房源浏览记录
     *
     * @return void
     */
    public function get_goods_look_log($page = 1 ,$limit=10){
        
        $list = Db::name('goods_look_log')->where(['uid'=>$this->auth->id])->order('time desc')->page($page,$limit)->select();
        if($list){
            foreach ($list as $key => &$val) {
                $val['goods'] = $this->GetGoodsData($val['goods_id']);
            }
        }
        $this->success('ok',$list);
    }


    /**
     * 获取我的分享二维码
     *
     * @return void
     */
    public function get_my_share_qr()
    {
        $Qrcode = new Qrcode();
        // $Qrcode->user_get_my_qr();
        return $Qrcode->user_get_my_qr($this->auth->id);
    }




    /**
     * 修改关注商品
     *
     * @param int $goods_id 商品id
     * @return void
     */
    public function update_gz_goods($goods_id)
    {
       

        $json['code'] = -1;
        $json['msg'] = '请传递正确参数！没有此商品';
        $goods = Db::name('goods')->where('id',$goods_id)->find();

        if(!$goods){
            return json($json);
        }

        // $this->is_uid();
        $data['uid'] = $this->auth->id;
        $data['goods_id'] = $goods_id;
        $res = Db::name('goods_gz')
            ->where($data)
            ->find();  
        
        if($res){
            $del = Db::name('goods_gz')->where($data)->delete();
            if($del){
                $json['code'] = 1;
                $json['status'] = 0;
                $json['msg'] = '已取消关注';
                // $Dec = Db::name('goods')->where('id',$goods_id)->setDec('gz_num');//关注数减
            }
        }else{            
            $data['time'] = time();
            $add = Db::name('goods_gz')->insert($data);
            if($add){
                $json['code'] = 1;
                $json['status'] = 1;
                $json['msg'] = '已关注';
                // $Inc = Db::name('goods')->where('id',$goods_id)->setInc('gz_num');//关注数加

                //提醒某个用户未读消息  消息类型:0=未知,1=作品评论,2=订单评论,3=作品点赞,4=关注手艺人
                // $this->add_unread_msg($data['goods_id'],4);
            }
        }
        return json($json);
    
    } 


    /**
     * 获取我关注的商品列表
     *
     * @param integer $page 1
     * @param integer $limit 9999
     * @param string $now_status 现房:1=现房,2=准现房,3=新房,4=商铺,5=租房,6=二手房
     * @return void
     */
    public function get_my_gz_goods_list($page=1,$limit=9999,$now_status = null)
    {
        $where = null;
        $goods_ids = Db::name('goods_gz')
            ->where('uid',$this->auth->id)
            ->column('goods_id');
            if($now_status){
                $where['now_status'] = ['=',$now_status];
            }
        $goods_list = Db::name('goods')
                ->where($where)
                ->where('id','in',$goods_ids)
                ->select();
        $this->success('ok',$goods_list);
    }


    /**
     * 获取商品信息——带关注
     *
     * @param int $goods_id 房源id
     * @return void
     */
    public function get_goods_data($goods_id)
    {
        $data = $this->GetGoodsData($goods_id);
        $data['goods_gz'] = Db::name('goods_gz')->where('uid',$this->auth->id)->where('goods_id',$goods_id)->find();//null;
        $this->AddGoodsLookLog($goods_id,$this->auth->id);
        $this->success('ok',$data);
    }

    /**
     * 删除查看记录
     *
     * @param int $id 记录id
     * @return void
     */
    public function del_look_log($id)
    {
        if($this->DelGoodsLookLog($id,$this->auth->id)){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }




    /**
     * 获取房产资讯信息带点赞👍
     *
     * @param int $id id
     * @return void
     */
    public function get_art_data($id)
    {
        $data['id'] = $id;
        $res = Db::name('art')
            ->where($data)
            ->field([ '*,FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%i:%s") as date'])
            ->find();
        if($res)$this->AddArtView($id);
        $res['good'] = $this->GetGoodData($id,$this->auth->id);
        $this->success('ok',$res);
    }

    /**
     * 文章点赞👍
     *
     * @param int $id 文章id
     * @param string $status 1=点赞,2=不好
     * @return void
     */
    public function art_good($id,$status='1')
    {
        $res = $this->GetGoodData($id,$this->auth->id);
        if($res){
            if($status=='1'){
                switch ($res['status']) {
                    case '1':
                        $this->error('你已点过赞',$res);
                        break;
                    case '2':
                        $this->IncArtGood($id,$this->auth->id);
                        $this->DecArtNoGood($id,$this->auth->id);
                        break;
                    
                    default:
                        # code...
                        break;
                }
            }elseif($status=='2'){
                switch ($res['status']) {
                    case '1':
                        $this->IncArtNoGood($id,$this->auth->id);
                        $this->DecArtGood($id,$this->auth->id);
                        break;
                    case '2':
                        $this->error('你已点过不好',$res);
                        
                        break;
                    
                    default:
                        # code...
                        break;
                }
            }
          
        }else{
            switch ($status) {
                case '1':
                    $this->IncArtGood($id,$this->auth->id);
                    break;
                
                default:
                    $this->IncArtNoGood($id,$this->auth->id);
                    break;
            }
            
        }


        $this->success('ok');
    }

}